﻿using BootstrapBlazor.Components;
using BPM.Web.Shared.Data;
using BPM.Web.Shared.Dependencies;
using BPM.Web.Shared.Extensions;
namespace BPM.Web.Shared.Service;

[Scoped(typeof(ISysTenantService))]
public class SysTenantService : BaseService, ISysTenantService
{
    private readonly IMenuClient _menuClient;
    private readonly ITenantClient _tenantClient;
    public SysTenantService(IMenuClient menuClient, ITenantClient tenantClient, ToastService toast) : base(toast)
    {
        _menuClient = menuClient;
        _tenantClient = tenantClient;
    }

    public Task<QueryData<TenantOutput>> PageAsync(TenantPageInput input)
        => QueryAsync(_tenantClient.PageAsync(input));

    public Task<bool> AddAsync(TenantOutput input)
        => ExecuteAsync(_tenantClient.AddAsync(input.Adapt<AddTenantInput>()));
    public Task<bool> DeleteAsync(TenantOutput input)
        => ExecuteAsync(_tenantClient.DeleteAsync(input.Adapt<DeleteTenantInput>()));
    public Task<bool> DeleteAsync(IEnumerable<TenantOutput> input)
        => DeleteAsync(input.Adapts<TenantOutput, DeleteTenantInput>().Select(x => _tenantClient.DeleteAsync(x)));

    public Task<bool> EditAsync(TenantOutput input)
        => ExecuteAsync(_tenantClient.EditAsync(input.Adapt<UpdateTenantInput>()));

    public Task<SysTenant?> DetailAsync(TenantOutput input)
        => QueryAsync(_tenantClient.DetailAsync(input.Adapt<QueryTenantInput>()));

    public Task<bool> GrantMenuAsync(IEnumerable<long>? grantMenuIdList, TenantOutput input)
    {
        if (grantMenuIdList == null)
        {
            return Task.FromResult(false);
        }

        var argument = input.Adapt<GrantRoleMenuInput>();
        argument.GrantMenuIdList = grantMenuIdList;
        return ExecuteAsync(_tenantClient.GrantMenuAsync(argument));
    }

    public List<TreeItem> OwnMenu(TenantOutput input)
        => AsyncExtensions.FactoryInvokeAndWait(async () =>
        {
            var ids = await QueryAsync(_tenantClient.OwnMenuAsync(input.Adapt<QueryTenantInput>()));
            var menus = await QueryAsync<List<MenuTreeOutput>>(_menuClient.TreeForGrantAsync(new()));
            return menus.BuildTree<MenuTreeOutput, long>((x, r) =>
            {
                r.Key = x.Id;
                r.Text = x.Title;
                r.HasChildNode = x.Children.Any();
                r.IsCollapsed = x.Children.Any();
                r.Checked = ids?.Contains(x.Id) == true;
            });
        });

    public Task<bool> ResetPwdAsync(TenantOutput input)
        => ExecuteAsync(_tenantClient.ResetPwdAsync(input.Adapt<QueryTenantInput>()));
}

